package com.qinggeng.project.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qinggeng.common.exception.CustomException;
import com.qinggeng.common.redenvelop.BigDecimalUtil;
import com.qinggeng.common.utils.CalendarAdjustUtils;
import com.qinggeng.framework.config.thread.ThreadPoolExecutorUtil;
import com.qinggeng.project.api.dto.UserAccountConsumptionDTO;
import com.qinggeng.project.system.domain.UserAccountConsumptionMonth;
import com.qinggeng.project.system.dto.SysUserAccountConsumptionMonthDTO;
import com.qinggeng.project.system.mapper.UserAccountConsumptionMonthMapper;
import com.qinggeng.project.system.service.IUserAccountService;
import com.qinggeng.project.system.service.UserAccountConsumptionMonthService;
import com.sun.jna.platform.win32.OaIdl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Service
public class UserAccountConsumptionMonthServiceImpl implements UserAccountConsumptionMonthService {

    @Resource
    private UserAccountConsumptionMonthMapper userAccountConsumptionMonthMapper;
    @Resource
    private IUserAccountService  userAccountService;


    @Override
    public boolean insertUserAccountConsumption(UserAccountConsumptionMonth userAccountConsumption) {
        Date date =new Date();
        userAccountConsumption.setUpdateTime(date);
        userAccountConsumption.setCreateTime(date);
        return userAccountConsumptionMonthMapper.insertSelective(userAccountConsumption)>=1;
    }

    @Override
    public UserAccountConsumptionMonth getUserAccountConsumption(UserAccountConsumptionMonth userAccountConsumption) {
        Long userId=userAccountConsumption.getUserId();

        String month=userAccountConsumption.getCreateMonth();

        Example example =new Example(UserAccountConsumptionMonth.class);
        example.createCriteria()
                .andEqualTo("userId",userId)
                .andEqualTo("createMonth",month)
                .andEqualTo("status",0)
                .andEqualTo("delFlag",0);
        UserAccountConsumptionMonth consumption= userAccountConsumptionMonthMapper.selectOneByExample(example);
        return consumption;
    }

    @Override
    public boolean subUpdateUserAccountConsumption(UserAccountConsumptionDTO dto) {
        UserAccountConsumptionMonth userAccountConsumption= dto;
        dto.setCreateMonth(CalendarAdjustUtils.getMonthToStr());
        userAccountConsumption= getUserAccountConsumption(userAccountConsumption);
        if (null ==userAccountConsumption){
            return false;
        }
        Long userId=dto.getUserId();
        BigDecimal  money =new BigDecimal(dto.getMoney());
        Long id=userAccountConsumption.getId();
        dto.setId(id);
        ThreadPoolExecutor threadPoolExecutor=ThreadPoolExecutorUtil.getPoll();
        Future<String> futureLastMonth=  threadPoolExecutor.submit(() -> {
            final String futureLastMonthConsumption = userAccountService.futureLastMonthConsumption(userId);
            return futureLastMonthConsumption;
        });

        try {
            String lastMonthConsumption=futureLastMonth.get();
            boolean bl =new BigDecimal(lastMonthConsumption).compareTo(BigDecimal.ZERO)<=0;
            if (bl){
                lastMonthConsumption=userAccountService.thisLastMonthMoney()
                        .setScale(2,BigDecimal.ROUND_UP).toString();
            }
            BigDecimal bigDecimalLastMonthConsumption= new BigDecimal(lastMonthConsumption);
            dto.setLastMonthConsumption(bigDecimalLastMonthConsumption);
            //這個月消費
            dto.setThisMonthConsumption(money);
            //這個月即将消费 计算还需消费多少
            BigDecimal thisMonthConsumption=  userAccountConsumption.getThisMonthConsumption();
            thisMonthConsumption=BigDecimalUtil.subtract(thisMonthConsumption,money);
            BigDecimal thisMonthNeedToConsume=BigDecimalUtil.subtract(bigDecimalLastMonthConsumption,thisMonthConsumption);

            //计算还需支付比例
            BigDecimal thisMonthNeedToConsumePercentage=BigDecimal.ONE;
            //本月可以提现
            BigDecimal thisMonthCanBeWifthdrawn=BigDecimal.ZERO;

            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)<=0){
                thisMonthNeedToConsume=BigDecimal.ZERO;
            }
            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)>0){
                thisMonthNeedToConsume=thisMonthNeedToConsume.abs();
                thisMonthNeedToConsumePercentage=BigDecimalUtil.divide(thisMonthConsumption,bigDecimalLastMonthConsumption);
            }

            thisMonthCanBeWifthdrawn=BigDecimalUtil.multiply(thisMonthConsumption,userAccountService.thisMonthProportion());

            dto.setThisMonthNeedToConsume(thisMonthNeedToConsume);
            dto.setThisMonthNeedToConsumePercentage(thisMonthNeedToConsumePercentage);
            //这个月可以提现
            dto.setThisMonthCanBeWifthdrawn(thisMonthCanBeWifthdrawn);

        }catch (Exception e){
            throw  new CustomException("统计错误 "+e.getMessage());
        }
        return userAccountConsumptionMonthMapper.subUpdateUserAccountConsumption(dto)>=1;

    }

    @Override
    public boolean goToSmallChange(UserAccountConsumptionDTO dto) {
        dto.setCreateMonth(CalendarAdjustUtils.getLastMonthToStr());

        return userAccountConsumptionMonthMapper.goToSmallChange(dto)>=1;
    }

    @Override
    public boolean goToSmallChangeClean(UserAccountConsumptionDTO dto) {
        dto.setCreateMonth(CalendarAdjustUtils.getLastMonthToStr());

        return userAccountConsumptionMonthMapper.goToSmallChangeClean(dto)>=1;
    }

    @Override
    public List<UserAccountConsumptionMonth> listLastMonthUserAccountConsumptionMonth() {
        Example example=new Example(UserAccountConsumptionMonth.class);
        example.createCriteria().andEqualTo("createMonth",CalendarAdjustUtils.getLastMonthToStr());
        return userAccountConsumptionMonthMapper.selectByExample(example);
    }

    @Override
    public List<UserAccountConsumptionMonth> listThisMonthUserAccountConsumptionMonth() {
        Example example=new Example(UserAccountConsumptionMonth.class);
        example.createCriteria().andEqualTo("createMonth",CalendarAdjustUtils.getMonthToStr());
        return userAccountConsumptionMonthMapper.selectByExample(example);
    }

    @Override
    public boolean updateUserAccountYearConsumptionStatus(Long id) {
        UserAccountConsumptionMonth month =new UserAccountConsumptionMonth();
        month.setId(id);
        month.setComputionYearStatus(1);
        month.setThisMonthCanBeWifthdrawn(new BigDecimal(UserAccountServiceImpl.ZERO));
        return userAccountConsumptionMonthMapper.updateByPrimaryKeySelective(month)>=1;
    }

    @Override
    public List<UserAccountConsumptionMonth> listSysThisMonthUserAccountConsumptionMonth(SysUserAccountConsumptionMonthDTO dto) {
        PageHelper.startPage(dto.getPageNum(),dto.getPageSize());
        return userAccountConsumptionMonthMapper.selectAll();
    }

    @Override
    public boolean updateUserAccountConsumption(Long userId) {
        UserAccountConsumptionMonth account =new UserAccountConsumptionMonth();
        account.setUserId(userId);
        account.setCreateMonth(CalendarAdjustUtils.getMonthToStr());

        UserAccountConsumptionMonth month=getUserAccountConsumption(account);

        ThreadPoolExecutor threadPoolExecutor=ThreadPoolExecutorUtil.getPoll();
        Future<String> futureLastMonth=  threadPoolExecutor.submit(() -> {
            final String futureLastMonthConsumption = userAccountService.futureLastMonthConsumption(userId);
            return futureLastMonthConsumption;
        });

        try {
            String lastMonthConsumption=futureLastMonth.get();
            BigDecimal bigDecimalLastMonthConsumption= new BigDecimal(lastMonthConsumption);
            boolean bl =bigDecimalLastMonthConsumption.compareTo(BigDecimal.ZERO)<=0;
            if (bl){
                lastMonthConsumption=userAccountService.thisLastMonthMoney()
                        .setScale(2,BigDecimal.ROUND_UP).toString();
            }
            //這個月即将消费 计算还需消费多少
            String thisMonthConsumption=  userAccountService.futureThisMonthConsumption(userId);
            BigDecimal bigDecimalThisMonthConsumption=new BigDecimal(thisMonthConsumption);
            BigDecimal thisMonthNeedToConsume=BigDecimalUtil.subtract(bigDecimalLastMonthConsumption,bigDecimalThisMonthConsumption);

            //计算还需支付比例
            BigDecimal thisMonthNeedToConsumePercentage=BigDecimal.ONE;
            //本月可以提现
            BigDecimal thisMonthCanBeWifthdrawn=BigDecimal.ZERO;

            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)<=0){
                thisMonthNeedToConsume=BigDecimal.ZERO;
            }
            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)>0){
                thisMonthNeedToConsume=thisMonthNeedToConsume.abs();
                thisMonthNeedToConsumePercentage=BigDecimalUtil.divide(bigDecimalThisMonthConsumption,bigDecimalLastMonthConsumption);
            }
            thisMonthCanBeWifthdrawn=BigDecimalUtil.multiply(bigDecimalThisMonthConsumption,userAccountService.thisMonthProportion());
            month.setLastMonthConsumption(new BigDecimal(lastMonthConsumption));
            month.setThisMonthNeedToConsume(thisMonthNeedToConsume);
            month.setThisMonthNeedToConsumePercentage(thisMonthNeedToConsumePercentage);
            month.setThisMonthConsumption(bigDecimalThisMonthConsumption);
            month.setThisMonthCanBeWifthdrawn(thisMonthCanBeWifthdrawn);

            //这个月可以提现

        }catch (Exception e){
            throw  new CustomException("统计错误 "+e.getMessage());
        }
        return userAccountConsumptionMonthMapper.updateByPrimaryKeySelective(month)>=1;

    }

    @Override
    public boolean addUpdateUserAccountConsumption(UserAccountConsumptionDTO dto) {
        UserAccountConsumptionMonth userAccountConsumption= dto;
        dto.setCreateMonth(CalendarAdjustUtils.getMonthToStr());
        userAccountConsumption= getUserAccountConsumption(userAccountConsumption);
        if (null ==userAccountConsumption){
            return false;
        }
        Long userId=dto.getUserId();
        BigDecimal  money =new BigDecimal(dto.getMoney());
        Long id=userAccountConsumption.getId();
        dto.setId(id);
        String lastMonthConsumption = userAccountService.futureLastMonthConsumption(userId);
        try {
            boolean bl =new BigDecimal(lastMonthConsumption).compareTo(BigDecimal.ZERO)<=0;
            if (bl){
                lastMonthConsumption=userAccountService.thisLastMonthMoney()
                        .setScale(2,BigDecimal.ROUND_UP).toString();
            }
            BigDecimal bigDecimalLastMonthConsumption= new BigDecimal(lastMonthConsumption);
            dto.setLastMonthConsumption(bigDecimalLastMonthConsumption);
            //這個月消費
            dto.setThisMonthConsumption(money);
            //這個月即将消费 计算还需消费多少
            BigDecimal thisMonthConsumption=  userAccountConsumption.getThisMonthConsumption();
            thisMonthConsumption=BigDecimalUtil.add(thisMonthConsumption,money);
            BigDecimal thisMonthNeedToConsume=BigDecimalUtil.subtract(bigDecimalLastMonthConsumption,thisMonthConsumption);

            //计算还需支付比例
            BigDecimal thisMonthNeedToConsumePercentage=BigDecimal.ONE;
            //本月可以提现
            BigDecimal thisMonthCanBeWifthdrawn=BigDecimal.ZERO;

            //还需消费小于0
            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)<=0){
                thisMonthNeedToConsume=BigDecimal.ZERO;
            }
            if (thisMonthNeedToConsume.compareTo(BigDecimal.ZERO)>0){
                thisMonthNeedToConsume=thisMonthNeedToConsume.abs();
                thisMonthNeedToConsumePercentage=BigDecimalUtil.divide(thisMonthConsumption,bigDecimalLastMonthConsumption);
            }

            thisMonthCanBeWifthdrawn=BigDecimalUtil.multiply(thisMonthConsumption,userAccountService.thisMonthProportion());


            dto.setThisMonthNeedToConsume(thisMonthNeedToConsume);
            dto.setThisMonthNeedToConsumePercentage(thisMonthNeedToConsumePercentage);
            //这个月可以提现
            dto.setThisMonthCanBeWifthdrawn(thisMonthCanBeWifthdrawn);

        }catch (Exception e){
            throw  new CustomException("统计错误 "+e.getMessage());
        }
        return userAccountConsumptionMonthMapper.addUpdateUserAccountConsumption(dto)>=1;

    }
    @Override
    public boolean checkUserAccountConsumption(UserAccountConsumptionMonth userAccountConsumption) {
        Long userId=userAccountConsumption.getUserId();
        if (null ==userId){
            throw  new CustomException("userId不能为空");
        }
        userAccountConsumption.setCreateMonth(CalendarAdjustUtils.getMonthToStr());

        UserAccountConsumptionMonth consumption=getUserAccountConsumption(userAccountConsumption);
        if (null  == consumption){

            userAccountConsumption.setThisMonthLuckDrawUrl(userAccountService.thisMonthLuckDrawUrl());
            return  insertUserAccountConsumption(userAccountConsumption);
        }
        return  true;
    }
}
